{template '_header'}
<div class="page-heading">
	
	<span class='pull-right'>
		
		{ifp 'task.add'}
           <a class="btn btn-primary btn-sm" href="{php echo webUrl('task/add',array('task_type'=>1))}">添加新海报</a>
           <a class='btn btn-primary btn-sm' href="{php echo webUrl('task/add',array('task_type'=>2))}">添加多级海报</a>
		{/if}

		<a class="btn btn-default  btn-sm" href="{php echo webUrl('task')}">返回列表</a>


	</span>
	<h2>{if !empty($item['id'])}编辑{else}添加{/if}海报 <small>{if !empty($item['id'])}修改【{$item['title']}】{/if}</small></h2>
</div>

<script language='javascript' src="../addons/ewei_shopv2/plugin/task/static/js/designer.js"></script>

<style type='text/css'>
    #task {
        width:320px;height:504px;border:1px solid #ccc;position:relative
    }
   #task .bg { position:absolute;width:100%;z-index:0}
   #task .drag[type=img] img,#task .drag[type=thumb] img { width:100%;height:100%; }
   {ife 'task' $item}
   #task .drag { position: absolute; width:80px;height:80px; border:1px solid #000; }
   {else}
   #task .drag { position: absolute; width:80px;height:80px; }
   {/if}

    #task .drag[type=nickname],#task .drag[type=time] { width:80px;height:40px; font-size:16px; font-family: 黑体;}
    #task .drag img {position:absolute;z-index:0;width:100%; }

    #task .rRightDown,.rLeftDown,.rLeftUp,.rRightUp,.rRight,.rLeft,.rUp,.rDown{
            position:absolute;
            width:7px;
            height:7px;
            z-index:1;
            font-size:0;
    }

    {ife 'task' $item}
       #task .rRightDown,.rLeftDown,.rLeftUp,.rRightUp,.rRight,.rLeft,.rUp,.rDown{
              background:#C00;
       }
    {/if}
    .rLeftDown,.rRightUp{cursor:ne-resize;}
    .rRightDown,.rLeftUp{cursor:nw-resize;}
    .rRight,.rLeft{cursor:e-resize;}
    .rUp,.rDown{cursor:n-resize;}
    .rLeftDown{left:-4px;bottom:-4px;}
    .rRightUp{right:-4px;top:-4px;}
    .rRightDown{right:-4px;bottom:-4px;}
       {ife 'task' $item}
            .rRightDown{background-color:#00F;}
       {/if}

    .rLeftUp{left:-4px;top:-4px;}
    .rRight{right:-4px;top:50%;margin-top:-4px;}
    .rLeft{left:-4px;top:50%;margin-top:-4px;}
    .rUp{top:-4px;left:50%;margin-left:-4px;}
    .rDown{bottom:-4px;left:50%;margin-left:-4px;}
    .context-menu-layer { z-index:9999;}
    .context-menu-list { z-index:9999;}

</style>

    <form action="" method="post" class="form-horizontal form-validate" enctype="multipart/form-data">
        <input type="hidden" name="id" value="{$item['id']}" />
        <ul class="nav nav-arrow-next nav-tabs" id="myTab">
            <li {if $_GPC['tab']=='basic' || empty($_GPC['tab'])}class="active"{/if} ><a href="#tab_basic">基本</a></li>
            <li {if $_GPC['tab']=='design'}class="active"{/if} ><a href="#tab_design">设计</a></li>


            <li class="{if $_GPC['tab']=='reward'}active{/if}"><a href="#tab_reward">奖励</a></li>
            <li class="{if $_GPC['tab']=='resp'}active{/if}"><a href="#tab_resp">推送</a></li>
            <li class="{if $_GPC['tab']=='commission'}active{/if}"><a href="#tab_commission">分销</a></li>
        </ul>

        <div class="tab-content">
            <div class="tab-pane  {if $_GPC['tab']=='basic' || empty($_GPC['tab'])}active{/if}" id="tab_basic">{template 'task/post/rankbasic'}</div>
            <div class="tab-pane  {if $_GPC['tab']=='design'}active{/if}" id="tab_design">{template 'task/post/design'}</div>
            <div class="tab-pane  {if $_GPC['tab']=='resp'}active{/if}" id="tab_resp" >{template 'task/post/resp'}</div>
            <div class="tab-pane {if $_GPC['tab']=='reward'}active{/if}" id="tab_reward"  >{template 'task/post/rankreward'}</div>
            <div class="tab-pane {if $_GPC['tab']=='commission'}active{/if}" id="tab_commission"  >{template 'task/post/commission'}</div>
        </div>

        <div class="form-group"></div>
            <div class="form-group">
                    <label class="col-sm-2 control-label"></label>
                    <div class="col-sm-9 col-xs-12">
                           {ife 'task' $item}
                            <input type="submit" value="提交" class="btn btn-primary"  />
                            <input type="hidden" name="rec_reward_data" value="">
                            <input type="hidden" name="rec_reward_rank" value="">
                            <input type="hidden" name="sub_reward_data" value="">
                            <input type="hidden" name="poster_type" value="2" />
                            <input type="hidden" name="data" value="" />
                        {/if}
                       <input type="button" name="back" onclick='history.back()' {ifp 'task.add|task.edit'}style='margin-left:10px;'{/if} value="返回列表" class="btn btn-default" />
                    </div>
            </div>
    </form>

<script language='javascript'>
    require(['bootstrap'],function(){
        $('#myTab a').click(function (e) {
            e.preventDefault();
            $('#tab').val( $(this).attr('href'));
            $(this).tab('show');
        })
    });

	function showGoodsSelect(show){
		if(show){
			$('#goodsdiv').show();
		}
		else{
			$('#goodsdiv').hide();
		}
	}

    $('form').submit(function(){

        if($(':radio[name=type]:checked').val()=='4'){

             if($(':radio[name=paytype]:checked').val()=='1'){

                var recmoney = parseFloat($(':input[name=recmoney]').val());
                if( recmoney>0 ){
                        if(recmoney<1){
                            $(':input[name=recmoney]').focus();
                            tip.msgbox.err('微信企业付款需支付1元以上!');
                            $('form').attr('stop',1);
                            return false;
                        }
                }
                var submoney = parseFloat($(':input[name=submoney]').val());
                if(submoney>0){
                    if(submoney<1){
                        $(':input[name=submoney]').focus();
                        tip.msgbox.err('微信企业付款需支付1元以上!');
                        $('form').attr('stop',1);
                        return false;
                    }
                }
             }
        }
        var data = [];
        $('.drag').each(function(){
            var obj = $(this);
            var type = obj.attr('type');
            var left = obj.css('left'),top = obj.css('top');
            var d= {left:left,top:top,type:obj.attr('type'),width:obj.css('width'),height:obj.css('height')};
            if(type=='nickname' ||type=='title' || type=='marketprice' || type=='productprice' ){
                d.size = obj.attr('size');
                d.color = obj.attr('color');
            } else if(type=='time'){
                d.title = obj.attr('title');
                d.size = obj.attr('size');
                d.color = obj.attr('color');
            } else if(type=='qr'){
                d.size = obj.attr('size');
            } else if(type=='img'){
                d.src = obj.attr('src');
            }else if(type=='head'){
                d.head_type=obj.attr('head_type');
            }
            data.push(d);
        });

        $(':input[name=data]').val( JSON.stringify(data));

        var rec_reward = [];
        $('.rec_reward_data').each(function () {
            var obj = $(this);
            var type = obj.data('type');
            var d = {};
            d.rank = obj.data('rank');
            if(type==1){
                d.type=1;
                d.num=obj.data('value');
            }else if(type==2){
                d.type=2;
                d.num=obj.data('value');
                d.moneytype=obj.data('moneytype');
            }else if(type==3){
                d.type=3;
                d.num=obj.data('value');
                if(d.num<1){
                    tip.msgbox.err('微信企业付款需支付1元以上!');
                    $('form').attr('stop',1);
                    return false;
                }
            }else if(type==4){
                d.type=4;
                d.goods_id=obj.data('goodsid');
                d.goods_name = obj.data('goodsname');
                d.goods_price = obj.data('goodsprice');
                var goods_spec = obj.data('goodsec');
                if(goods_spec>0){
                    d.goods_spec = goods_spec;
                    d.goods_specname = obj.data('specname');
                }else{
                    d.goods_spec = 0;
                    d.goods_specname = '无规格';
                }
                d.goods_total = obj.data('goodsnum');
            }else if(type==5){
                d.type=5;
                d.coupon_id=obj.data('couponid');
                d.coupon_name=obj.data('couponname');
                d.coupon_num=obj.data('couponnum');
            }
            rec_reward.push(d);
        });

        var rec_reward_rank = [];
        $('#rec-rank .panel').each(function () {
            var obj = $(this);
            var rank_state = obj.data('state');
            var d = {};
            d.rank = obj.data('rank');
            d.rank_state = parseInt(rank_state);
            d.needcount = obj.data('needcount');
            rec_reward_rank.push(d);
        });

        $('input[name="rec_reward_data"]').val( JSON.stringify(rec_reward));
        $('input[name="rec_reward_rank"]').val( JSON.stringify(rec_reward_rank));

        var sub_reward = [];
        $('.sub_reward_data').each(function () {
            var obj = $(this);
            var type = obj.data('type');
            var d = {};
            if(type==1){
                d.type=1;
                d.num=obj.data('value');
            }else if(type==2){
                d.type=2;
                d.num=obj.data('value');
                d.moneytype=obj.data('moneytype');
            }else if(type==3){
                d.type=3;
                d.num=obj.data('value');
                if(d.num<1){
                    tip.msgbox.err('微信企业付款需支付1元以上!');
                    $('form').attr('stop',1);
                    return false;
                }
            }else if(type==5){
                d.type=5;
                d.coupon_id=obj.data('couponid');
                d.coupon_name=obj.data('couponname');
                d.coupon_num=obj.data('couponnum');
            }
            sub_reward.push(d);
        });
        $('input[name="sub_reward_data"]').val( JSON.stringify(sub_reward));
        $('form').removeAttr('stop');
        return true;

    });

        function bindEvents(obj){

            var index = obj.attr('index');

            var rs = new Resize(obj, { Max: true, mxContainer: "#task" });
            rs.Set($(".rRightDown",obj), "right-down");
            rs.Set($(".rLeftDown",obj), "left-down");
            rs.Set($(".rRightUp",obj), "right-up");
            rs.Set($(".rLeftUp",obj), "left-up");
            rs.Set($(".rRight",obj), "right");
            rs.Set($(".rLeft",obj), "left");
            rs.Set($(".rUp",obj), "up");
            rs.Set($(".rDown",obj), "down");
            rs.Scale = true;
            var type = obj.attr('type');
            if(type=='nickname' || type=='img' || type=='title' || type=='marketprice' || type=='productprice' || type=='time'){
                rs.Scale = false;
            }
            new Drag(obj, { Limit: true, mxContainer: "#task" });
            $('.drag .remove').unbind('click').click(function(){
                $(this).parent().remove();
            })
          myrequire(['jquery.contextMenu'],function(){
         $.contextMenu({
                selector: '.drag[index=' + index + ']',
                callback: function(key, options) {
                    var index = parseInt($(this).attr('zindex'));

                    if(key=='next'){
                        var nextdiv = $(this).next('.drag');
                        if(nextdiv.length>0 ){
                           nextdiv.insertBefore($(this));
                        }
                    } else if(key=='prev'){
                        var prevdiv = $(this).prev('.drag');
                        if(prevdiv.length>0 ){
                           $(this).insertBefore(prevdiv);
                        }
                    } else if(key=='last'){
                        var len = $('.drag').length;
                         if(index >=len-1){
                            return;
                        }
                        var last = $('#task .drag:last');
                        if(last.length>0){
                           $(this).insertAfter(last);
                        }
                    }else if(key=='first'){
                        var index = $(this).index();
                        if(index<=1){
                            return;
                        }
                        var first = $('#task .drag:first');
                        if(first.length>0){
                           $(this).insertBefore(first);
                        }
                    }else if(key=='delete'){
                       $(this).remove();
                    }
                    var n =1 ;
                    $('.drag').each(function(){
                        $(this).css("z-index",n);
                        n++;
                    })
                },
                items: {
                    "next": {name: "调整到上层"},
                    "prev": {name: "调整到下层"},
                    "last": {name: "调整到最顶层"},
                    "first": {name: "调整到最低层"},
                    "delete": {name: "删除元素"}
                }
            });
            obj.unbind('click').click(function(){
                bind($(this));
            })

              });

        }
   var imgsettimer = 0 ;
   var nametimer = 0;
   var bgtimer = 0 ;
         function bindType(type){
             $("#goodsparams").hide();
             $(".type4").hide();
             if(type=='4'){
                 $(".type4").show();
             } else if(type=='3'){
                    $("#goodsparams").show();
             }
         }
         function clearTimers(){
           clearInterval(imgsettimer);
           clearInterval(nametimer);
           clearInterval(bgtimer);

         }
         function getImgUrl(val){

              if(val.indexOf('http://')==-1){
                  val = "{$imgroot}" + val;
              }
              return val;
         }
         function bind(obj){
            var imgset = $('#imgset'), nameset = $("#nameset"),qrset = $('#qrset'),head = $('#headset'),time=$('#timeset');
             imgset.hide(),nameset.hide(),qrset.hide();head.hide(),time.hide();
             clearTimers();
               var type = obj.attr('type');
               if(type=='img'){
                   imgset.show();
                   var src = obj.attr('src');
                   var input = imgset.find('input');
                   var img = imgset.find('img');
                   if(typeof(src)!='undefined' && src!=''){
                       input.val(src);
                       img.attr('src',getImgUrl(src));
                  }

                   imgsettimer = setInterval(function(){
                       if(input.val()!=src && input.val()!=''){
                           var url = getImgUrl(input.val());

                           obj.attr('src',input.val()).find('img').attr('src',url);
                       }
                   },10);

             } else if(type=='nickname' || type=='title' || type=='marketprice' || type=='productprice' ){

                  nameset.show();
                  var color = obj.attr('color') || "#000";
                  var size = obj.attr('size') || "16";
                  var input = nameset.find('input:first');
                  var namesize = nameset.find('#namesize');
                  var picker = nameset.find('.sp-preview-inner');
                  input.val(color); namesize.val(size.replace("px",""));
                  picker.css( {'background-color':color,'font-size':size});

                  nametimer = setInterval(function(){
                       obj.attr('color',input.val()).find('.text').css('color',input.val());
                       obj.attr('size',namesize.val() +"px").find('.text').css('font-size',namesize.val() +"px");
                   },10);

             }else if(type=='time'){
                   time.show();
                   var color = obj.attr('color') || "#000";
                   var size = obj.attr('size') || "16";
                   var title = time.find('#timename');
                   var input = time.find('input[name="color"]');
                   var namesize = time.find('#timesize');
                   var picker = time.find('.sp-preview-inner');
                   input.val(color); namesize.val(size.replace("px",""));
                   picker.css( {'background-color':color,'font-size':size});

                   nametimer = setInterval(function(){
                       obj.attr('title',title.val());
                       obj.attr('color',input.val()).find('.text').css('color',input.val()).html(title.val());
                       obj.attr('size',namesize.val() +"px").find('.text').css('font-size',namesize.val() +"px");
                   },10);

             }else if(type=='qr'){
                 qrset.show();
                 var size = obj.attr('size') || "3";
                 var sel = qrset.find('#qrsize');
                 sel.val(size);
                 sel.unbind('change').change(function(){
                      obj.attr('size',sel.val())
                 });
             }else if(type=='head'){
//                 head.show();
//                 $('.head_set').click(function () {
//                     var type = $(this).attr('type');
//                     if(type=='default'){
//                         obj.find('img:first').attr('class','');
//                         obj.attr('head_type','default');
//                     }else if(type=='img-rounded'){
//                         obj.find('img:first').attr('class','img-rounded');
//                         obj.attr('head_type','rounded');
//                     }else if(type=='img-circle'){
//                         obj.find('img:first').attr('class','img-circle');
//                         obj.attr('head_type','circle');
//
//                     }
//                 });
             }
         }

    $(function(){
        {if !empty($item['id'])}
               {ife 'task' $item}
          $('.drag').each(function(){
              bindEvents($(this));
          })
          {/if}
        {/if}

            $(':radio[name=type]').click(function(){
                var type = $(this).val();
                bindType(type);
            })

        $(':radio[name=resptype]').click(function(){
            var type = $(this).val();
            if(type == 1)
            {
                $(".resptype1").show();
                $(".resptype0").hide();
            }
            else
            {
                $(".resptype0").show();
                $(".resptype1").hide();
            }
        })
        //改变背景
        $('#bgset').find('button:first').click(function(){
            var oldbg = $(':input[name=bg]').val();
            bgtimer = setInterval(function(){
                 var bg = $(':input[name=bg]').val();
                 if(oldbg!=bg){
                 	  bg = getImgUrl(bg);

                      $('#task .bg').remove();
                      var bgh = $("<img src='" + bg + "' class='bg' />");
                       var first = $('#task .drag:first');
                        if(first.length>0){
                           bgh.insertBefore(first);
                        } else{
                           $('#task').append(bgh);
                        }

                      oldbg = bg;
                 }
            },10);
        })

        $('.btn-com').click(function(){

           var imgset = $('#imgset'), nameset = $("#nameset"),qrset = $('#qrset');
           imgset.hide(),nameset.hide(),qrset.hide();
           clearTimers();

            if($('#task img').length<=0){
                //alert('请选择背景图片!');
                //return;
            }
            var type = $(this).data('type');
            var img = "";
            if(type=='qr'){
                img = '<img src="../addons/ewei_shopv2/plugin/task/static/images/qr.jpg" />';
            }
            else if(type=='head'){
                img = '<img src="../addons/ewei_shopv2/plugin/task/static/images/head.jpg" />';
            }else  if(type=='img' || type=='thumb'){
                img = '<img src="../addons/ewei_shopv2/plugin/task/static/images/img.jpg" />';
            }
            else if(type=='nickname'){
                img = '<div class=text>昵称</div>';
            }
	        else if(type=='time'){
                img = '<div class=text>失效时间</div>';
            }  else if(type=='title'){
                img = '<div class=text>商品名称</div>';
            } else if(type=='marketprice'){
                img = '<div class=text>商品现价</div>';
            }else if(type=='productprice'){
                img = '<div class=text>商品原价</div>';
            }
            var index = $('#task .drag').length+1;
            var obj = $('<div class="drag" type="' + type +'" index="' + index +'" style="z-index:' + index+'">' + img+'<div class="rRightDown"> </div><div class="rLeftDown"> </div><div class="rRightUp"> </div><div class="rLeftUp"> </div><div class="rRight"> </div><div class="rLeft"> </div><div class="rUp"> </div><div class="rDown"></div></div>');

            $('#task').append(obj);
            
            bindEvents(obj);
            
        });
    
         $('.drag').click(function(){
               bind($(this))     ;
         })
        
    })
  //选择规格
  function spcselect(obj) {
      var select_option = $(obj).find("option:selected");
      var id= select_option.data('id');
      var marketprice= select_option.data('marketprice');
      var stock= select_option.data('stock');
      $('#marketprice_'+id).html(marketprice);
      $('#total_'+id).html(stock);
  }
	
    </script>
{template '_footer'}
